const { Tab } = require('../../assets/libs/zanui/index');

var app = getApp();
Page(Object.assign({}, Tab, {
  data: {
		cdnUrl: '',
		isHidden: true,
		
		region: ['省', '市', '区'],
		valueRegion: [0, 0, 0],
		cityId:0,
		district:[],
		multiArray:[],
		multiIndex: [0, 0, 0],
	
		/* 自定义导航栏参数 */
		loading: false,
		color: '#FFFFFF',
		background: '#FFFFFF',
		show: true,
		animated: false,
		back: true,
		title: "编辑地址",
		
		/* 地址表单 */
		/*定义订单表单元素*/
		addressForm:{
			id: 0,
		  name: '',
		  mobile: '',
		  address: '',//省/市/区的标志
		  address_detail: '',
		  defaultswitch: 0,//是否默认地址
			lat: '',
			lng: ''
		}
  },
	defaultswitchChange: function(e){
		var value = e.detail.value;
		this.setData({
			['addressForm.defaultswitch']: value
		})
	},
	addressDetailChange: function(e){
		var value = e.detail.value;
		this.setData({
			['addressForm.address_detail']: value
		})
	},
	nameChange: function(e){
		var value = e.detail.value;
		this.setData({
			['addressForm.name']: value
		})
	},
	mobileChange: function(e){
		var value = e.detail.value;
		this.setData({
			['addressForm.mobile']: value
		})
	},
	/* 提交地址表单信息 */
	submit: function (e){
		if (!app.globalData.userInfo) {
			app.showLoginModal(e);
		  // app.error("请登录后再操作");
		  return false;
		}
		var that = this;
		var form = that.data.addressForm;
		if(form.name=='') {
			app.error('请填写联系人姓名');
			return false;
		}
		if(form.mobile=='') {
			app.error('请填写联系人电话');
			return false;
		}
		if(form.address=='') {
			app.error('请选择地区');
			return false;
		}
		// if(form.address_detail=='') {
		// 	app.error('请填写详细地址');
		// 	return false;
		// }
		var formData = JSON.stringify(that.data.addressForm);
		app.request('/addons/cms/wxapp.user/addAddress', {data: formData}, function(data, ret) {
			app.success(ret.msg);
			setTimeout(function(){
				wx.navigateBack({});
			},2000)
		}, function(data, ret) {
		  app.error(ret.msg);
			return false;
		});
	},
  delAddress: function(){
  	/* 删除地址 */
		var that = this;
		var id = that.data.addressForm.id;
  	app.request('/addons/cms/wxapp.user/delAddress', {id: id}, function (data, ret) {//获取地址信息
  	  that.setData({
  	    ['addressForm.id']: 0,
  			['addressForm.name']: '',
  			['addressForm.mobile']: '',
  			['addressForm.address']: '',
				['addressForm.lat']: '',
				['addressForm.lng']: '',
  			['addressForm.address_detail']: '',
  			['addressForm.defaultswitch']: 0
  	  });
			app.success(ret.msg);
  	}, function (data, ret) {
			app.error(ret.msg);
  	});
  },
	onLoad: function (e) {
    var that = this;
		var id = e.id;
		/* 获取编辑地址 */
		app.request('/addons/cms/wxapp.user/addressDetail', {id: id}, function (data, ret) {//获取地址信息
		  that.setData({
		    ['addressForm.id']: data.id,
				['addressForm.name']: data.name,
				['addressForm.mobile']: data.mobile,
				['addressForm.address']: data.address,
				['addressForm.lat']: data.lat,
				['addressForm.lng']: data.lng,
				['addressForm.address_detail']: data.address_detail,
				['addressForm.defaultswitch']: data.defaultswitch
		  });
		}, function (data, ret) {
		});
		
		that.setData({
			cdnUrl: app.cdnUrl,
		});
   //  app.request('/addons/cms/wxapp.area/index', {}, function (data, ret) {//获取地址信息
   //    that.setData({
   //      district: data
   //    });
			// that.initialize();
   //  }, function (data, ret) {
   //    app.error(ret.msg);
   //  });
  },
  onShareAppMessage: function () {
    return {
      title: '',
      desc: '',
      path: '/page/index/index'
    }
  },
  
  initialize:function(){
    let that = this, province = [], city = [], area = [];
    if (that.data.district.length) {
      let cityChildren = that.data.district[0].c || [];
      let areaChildren = cityChildren.length ? (cityChildren[0].c || []) : [];
      that.data.district.forEach(function (item) {
        province.push(item.n);
      });
      cityChildren.forEach(function (item) {
        city.push(item.n);
      });
      areaChildren.forEach(function (item) {
        area.push(item.n);
      });
      that.setData({
        multiArray: [province, city, area],
      });
    }
  },
  bindRegionChange: function (e) {
    let multiIndex = this.data.multiIndex, province = this.data.district[multiIndex[0]] || { c: [] }, city = province.c[multiIndex[1]] || { v: 0 }, multiArray = this.data.multiArray, value = e.detail.value;
    console.log(value);
    console.log(province);
    this.setData({
			['addressForm.address']: multiArray[0][value[0]]+'/'+multiArray[1][value[1]]+'/'+multiArray[2][value[2]],
      region: [multiArray[0][value[0]], multiArray[1][value[1]], multiArray[2][value[2]]],
      cityId: city.v,
      valueRegion: [0,0,0]
    });
    this.initialize();
  },
  bindMultiPickerColumnChange:function(e){
    let that = this, column = e.detail.column, value = e.detail.value, currentCity = this.data.district[value] || { c: [] }, multiArray = that.data.multiArray, multiIndex = that.data.multiIndex;
    multiIndex[column] = value;
    switch (column){
      case 0:
        let areaList = currentCity.c[0] || { c: [] };
        multiArray[1] = currentCity.c.map((item)=>{
          return item.n;
        });
        multiArray[2] = areaList.c.map((item)=>{
          return item.n;
        });
      break;
      case 1:
        let cityList = that.data.district[multiIndex[0]].c[multiIndex[1]].c || [];
        multiArray[2] = cityList.map((item)=>{
          return item.n;
        });
      break;
      case 2:
      
      break;
    }
    this.setData({ multiArray: multiArray, multiIndex: multiIndex});
  },
  /* 弹窗 */
  showMd: function(e) {
      var that = this;
      // var id = e.currentTarget.dataset.id - 1;
      this.setData({
          isHidden: false,//显示模态框，
          // indexModel: that.data.modelList[id],
      })
  },
  hiddenMd: function() {
      this.setData({
          isHidden: true//隐藏模态框
      })
  },
	//地址选择
	choiceAddress: function (event) {
		var that = this;
		wx.chooseLocation({
			success: function (res) {
				console.log(res);
				that.getCityName(res.latitude,res.longitude);
				that.setData({
				
					['addressForm.address']: res.address,
					['addressForm.lat']: res.latitude,
					['addressForm.lng']: res.longitude
				})
			},
			fail: function (err) {
				wx.getSetting({
					success: function (res) {
						var statu = res.authSetting;
						if (!statu['scope.userLocation']) {
							wx.showModal({
								title: '是否授权当前位置',
								content: '需要获取您的地理位置，请确认授权，否则地图功能将无法使用',
								confirmColor: '#00cd85',
								cancelColor: '#333',
								success: function (tip) {
									if (tip.confirm) {
										wx.openSetting({
											success: function (data) {
												if (data.authSetting["scope.userLocation"] === true) {
													//授权成功之后，再调用chooseLocation选择地方
													wx.chooseLocation({
														success: function (res) {
															console.log(res)
															// var bigadr = res.name
															// if (bigadr == '') {
															// 	bigadr = res.address
															// }
															that.setData({
																['addressForm.address']: res.address,
																['addressForm.lat']: res.latitude,
																['addressForm.lng']: res.longitude
															})
														},
													})
												} else {
													app.showToast('授权失败');
												}
											}
										})
									}
								}
							})
						}
					},
					fail: function (res) {
						app.showToast('调用授权窗口失败');
					}
				})
			}
		})
	},
	getCityName(lat,lng){
    var that = this;
    app.request('/api/index/cityName', {
      latitude:lat,
      longitude:lng
    }, function (data, ret) {
        console.log("cityName",data);
				that.setData({
					['addressForm.address_text']: data.province+","+data.city+","+data.district
				})
				console.log("cityName",that.data.addressForm.address_text);
    }, function (data, ret) {
      
    });
  },
  //点击地址（搜索结果）
  checkAddress: function (event) {
    var that = this;
    let location = event.currentTarget.dataset.location;
    let lnglatarr = location.split(',');
    let lng = lnglatarr[0];
    let lat = lnglatarr[1];
    let name = event.currentTarget.dataset.name;
    that.setData({
      searchshow: 0,
      check_bigadr: name,
      check_lat: lat,
      check_lng: lng
    })
  },
}))
